package com.example.demo.core.base;

import com.example.demo.core.exception.NotFoundException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.*;


public class BaseServiceImpl<M extends BaseDao<T>, T> implements BaseService<T> {

    @Autowired
    protected M baseDao;

    public BaseServiceImpl() {

    }

    public M getBaseDao() {
        return this.baseDao;
    }

    @Override
    public Page<T> paging(Pageable pageable, HashMap<String, Object> queryMap) {
        Specification<T> specification = (Specification<T>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            for (Map.Entry<String, Object> queryEntry : queryMap.entrySet()) {
                Object value = queryEntry.getValue();
                if (value instanceof String) {
                    String stringValue = value.toString();
                    if (StringUtils.isNotBlank(stringValue)) {
                        //这里的问题是      equal 不固定  get 也不固定
                        predicates.add(cb.equal(root.get(queryEntry.getKey()), queryEntry.getValue().toString()));
                    }
                } else {
                    if (!Objects.isNull(value)) {
                        predicates.add(cb.equal(root.get(queryEntry.getKey()), queryEntry.getValue().toString()));
                    }
                }
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return baseDao.findAll(specification, pageable);
    }

    @Override
    public T save(T t) {
        return baseDao.save(t);
    }

    @Override
    public T get(Integer id) {
        return baseDao.findById(id).orElseThrow(() -> new NotFoundException("没有记录"));
    }

    @Override
    public T update(T t) {
        return baseDao.save(t);
    }

    @Override
    public Boolean delete(Integer id) {
        try {
            baseDao.deleteById(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<T> listAll(Sort sort) {
        if (sort == null) {
            return baseDao.findAll();
        } else {
            return baseDao.findAll(sort);
        }
    }

    @Override
    public Long count() {
        return baseDao.count();
    }


}
